<template>
  <div class="container">
    <!-- Header section -->
    <div class="header">
      <div class="search-bar">
        <input type="text" v-model="query" placeholder="查询" class="query-input" />
        <el-button type="primary" @click="search" class="header-button">
          <el-icon><Search /></el-icon>
          查询
        </el-button>
        <el-button type="success" @click="navigateToCreate" class="header-button">
          <el-icon><Plus /></el-icon>
          新建动态
        </el-button>
        <el-button type="danger" @click="undo" class="header-button" :disabled="deletedItems.length === 0">
          <el-icon><Close /></el-icon>
          撤销
        </el-button>
      </div>
    </div>

    <!-- Dynamic data table -->
    <el-table :data="paginatedItems" class="data-table" header-align="center" align="center">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="动态编号" width="120" align="center" class="text-center"></el-table-column>
      <el-table-column prop="title" label="标题" width="180" align="center" class="text-center">
        <template v-slot="scope">
          <el-link @click="showDynamicDetails(scope.row)">{{ scope.row.title }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="图片" width="100" align="center" class="text-center">
        <template v-slot="scope">
          <img :src="scope.row.newsImage" alt="图片" width="50" height="50" />
        </template>
      </el-table-column>
      <el-table-column prop="newsIntro" label="动态简介" width="250" align="center" class="text-center"></el-table-column>
      <el-table-column prop="author" label="作者" width="120" align="center" class="text-center"></el-table-column>
      <el-table-column prop="publishTime" label="发布时间" width="180" align="center" class="text-center">
        <template v-slot:header>
          <div @click="toggleSortOrder" class="sortable-header">
            发布时间
            <el-icon v-if="sortOrder === 'asc'"><ArrowUp /></el-icon>
            <el-icon v-if="sortOrder === 'desc'"><ArrowDown /></el-icon>
          </div>
        </template>
        <template v-slot="scope">
          {{ new Date(scope.row.publishTime).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center" class="text-center">
        <template v-slot="scope">
          <el-button-group class="operation-buttons">
            <el-button size="small" type="warning" @click="edit(scope.row)">
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button size="small" type="danger" @click="deleteRow(scope.row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- Pagination -->
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, ->, jumper, total"
        :total="filteredItems.length"
        :page-size="itemsPerPage"
        @current-change="handlePageChange"
      ></el-pagination>
      <el-select v-model="itemsPerPage" class="items-per-page-select">
        <el-option v-for="option in itemsPerPageOptions" :key="option" :label="option + ' / 页'" :value="option"></el-option>
      </el-select>
    </div>

    <!-- Edit Dynamic Dialog -->
    <el-dialog v-model="editDialogVisible" title="编辑动态" class="dialog">
      <!-- Edit form -->
      <el-form :model="editDynamic" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="editDynamic.title"></el-input>
        </el-form-item>
        <el-form-item label="动态简介">
          <el-input v-model="editDynamic.newsIntro"></el-input>
        </el-form-item>
        <el-form-item label="新闻图片">
          <img :src="editDynamic.newsImage" alt="新闻图片" width="100" height="100" @click="selectImage" />
          <input type="file" ref="fileInput" style="display: none" @change="handleImageChange" />
        </el-form-item>

        <el-form-item label="关键字">
          <el-input v-model="editDynamic.keywords"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="editDynamic.author"></el-input>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-input v-model="editDynamic.publishTime"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </div>
    </el-dialog>

    <!-- Dynamic Details Dialog -->
    <el-dialog v-model="detailDialogVisible" title="动态详细信息" width="80%" style="font: x-large;">
      <el-table :data="[selectedDynamic]" class="detail-table" border>
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column label="图片" width="250" align="center">
          <template v-slot="scope">
            <img
              :src="scope.row.newsImage"
              alt="动态图片"
              class="cover-image"
              @click="handlePictureCardPreview(scope.row.newsImage)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="author" label="作者"></el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="190" align="center">
          <template v-slot="scope">
            {{ new Date(scope.row.publishTime).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="keywords" label="关键字"></el-table-column>
        <el-table-column prop="newsIntro" label="动态简介" width="350" align="center" class="text-center"></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 图片预览弹窗 -->
    <el-dialog v-model="dialogPreviewVisible">
      <img class="preview-image" :src="selectedDynamic.newsImage" alt="Preview Image" style="width: 85%;" />
    </el-dialog>
  </div>
</template>


<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { Search, Plus, Edit, Delete, ArrowUp, ArrowDown, Close } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

interface Dynamic {
  id: string;
  title: string;
  newsImage: string;
  keywords: string;
  newsIntro: string;
  author: string;
  publishTime: string;
}

export default defineComponent({
  name: 'FieldDetail',
  components: {
    Search,
    Plus,
    Edit,
    Delete,
    ArrowUp,
    ArrowDown,
    Close
  },
  setup() {
    const query = ref('');
    const items = ref<Dynamic[]>([]);
    const deletedItems = ref<{item: Dynamic, deletedAt: number}[]>([]); // 用于存储已删除的动态和删除时间戳
    const currentPage = ref(1);
    const itemsPerPage = ref(10);
    const itemsPerPageOptions = [10, 20, 30];
    const sortOrder = ref<'asc' | 'desc' | null>('desc'); // 默认倒序排列
    const router = useRouter();
    const editDialogVisible = ref(false); // Dialog visibility state
    const editDynamic = ref<Dynamic>({
      id: '',
      title: '',
      newsImage: '',
      keywords: '',
      newsIntro: '',
      author: '',
      publishTime: ''
    }); // Edit form data

    const fileInput = ref<HTMLInputElement | null>(null);

    const selectImage = () => {
      if (fileInput.value) {
        fileInput.value.click();
      }
    };

    const saveEdit = async () => {
      try {
        await axios.put(`http://localhost:1111/api/dynamics/${editDynamic.value.id}`, editDynamic.value);
        const index = items.value.findIndex(item => item.id === editDynamic.value.id);
        if (index !== -1) {
          items.value[index] = { ...editDynamic.value };
        }
        editDialogVisible.value = false;
        ElMessage.success('动态更新成功'); // 添加更新成功的提示信息
      } catch (error) {
        console.error('Error updating dynamic:', error);
        ElMessage.error('动态更新失败'); // 添加更新失败的提示信息
      }
    };

    const detailDialogVisible = ref(false); // New detail dialog visibility state
    const selectedDynamic = ref<Dynamic>({
      id: '',
      title: '',
      newsImage: '',
      keywords: '',
      newsIntro: '',
      author: '',
      publishTime: ''
    }); // New selected dynamic data

    const dialogPreviewVisible = ref(false); // Image preview dialog visibility state

    onMounted(async () => {
      try {
        await fetchData();
      } catch (error) {
        console.error('Error fetching dynamics:', error);
      }
    });

    const fetchData = async () => {
      try {
        const response = await axios.get('http://localhost:1111/api/dynamics');
        items.value = response.data;
      } catch (error) {
        console.error('Error fetching dynamics:', error);
      }
    };

    const search = () => {
      console.log('Search query:', query.value);
    };

    const navigateToCreate = () => {
      router.push('/fieldcreat');
    };

    const toggleSortOrder = () => {
      sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
    };

    const handlePageChange = (page: number) => {
      currentPage.value = page;
    };

    const deleteRow = async (row: Dynamic) => {
      try {
        // 弹出确认框
        const confirmDelete = await ElMessageBox.confirm('确定要删除此动态吗？', '提示', {
          type: 'warning'
        });

        if (confirmDelete) {
          // 用户点击了确认按钮，执行删除操作
          await axios.delete(`http://localhost:1111/api/dynamics/${row.id}`);
          items.value = items.value.filter(item => item.id !== row.id);
          deletedItems.value.push({ item: row, deletedAt: Date.now() }); // 将删除的记录保存到栈中，并记录删除时间戳
          console.log('Deleted dynamic with ID:', row.id);
          ElMessage.success('删除成功');
        } else {
          // 用户点击了取消按钮，不执行任何操作
          console.log('取消删除');
        }
      } catch (error) {
        console.error('Error deleting dynamic:', error);
        ElMessage.error('删除失败');
      }
    };

    const undo = async () => {
      try {
        if (deletedItems.value.length > 0) {
          const deletedItem = deletedItems.value.pop();

          if (!deletedItem) {
            console.error('No item to restore');
            return;
          }

          const { item: lastDeletedItem } = deletedItem;

          // 构建请求体
          const requestBody = {
            dynamic: {
              id: lastDeletedItem.id,
              title: lastDeletedItem.title,
              newsImage: lastDeletedItem.newsImage,
              keywords: lastDeletedItem.keywords,
              newsIntro: lastDeletedItem.newsIntro,
              author: lastDeletedItem.author,
              publishTime: lastDeletedItem.publishTime
            }
          };

          // 发送恢复动态的 POST 请求
          const response = await axios.post('http://localhost:1111/api/dynamics', requestBody, {
            headers: { 'Content-Type': 'application/json' }
          });

          console.log('Restored dynamic response:', response.data);

          // 将恢复的动态添加回列表中
          items.value.push(response.data);

          // 删除成功后更新当前页
          await fetchData();
        } else {
          console.error('No deleted items to restore');
        }
      } catch (error) {
        console.error('Error restoring dynamic:', error);
      }
    };

    const edit = (row: Dynamic) => {
      editDynamic.value = { ...row };
      editDialogVisible.value = true;
    };

    const showDynamicDetails = (row: Dynamic) => {
      selectedDynamic.value = { ...row };
      detailDialogVisible.value = true;
    };

    const handlePictureCardPreview = (newsImage: string) => {
      selectedDynamic.value.newsImage = newsImage;
      dialogPreviewVisible.value = true;
    };

    const filteredItems = computed(() => {
      const queryLower = query.value.toLowerCase(); // 将查询字符串转为小写

      return items.value.filter(item => {
        // 确保每个 item 和其相关属性不为空
        if (!item || !item.title || !item.author || !item.newsIntro || !item.newsImage) {
          return false;
        }

        // 将每个属性转为小写后检查是否包含查询字符串
        return (
          item.title.toLowerCase().includes(queryLower) ||
          item.author.toLowerCase().includes(queryLower) ||
          item.newsIntro.toLowerCase().includes(queryLower) ||
          item.newsImage.toLowerCase().includes(queryLower)
        );
      });
    });

    const sortedItems = computed(() => {
      return filteredItems.value.slice().sort((a, b) => {
        if (sortOrder.value === 'asc') {
          return new Date(a.publishTime).getTime() - new Date(b.publishTime).getTime();
        } else if (sortOrder.value === 'desc') {
          return new Date(b.publishTime).getTime() - new Date(a.publishTime).getTime();
        } else {
          return 0;
        }
      });
    });

    const paginatedItems = computed(() => {
      const startIndex = (currentPage.value - 1) * itemsPerPage.value;
      return sortedItems.value.slice(startIndex, startIndex + itemsPerPage.value);
    });

    const handleImageChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    const file = target.files[0];
    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await axios.post('http://localhost:1111/api/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });

      if (response.data && response.data.url) {
        editDynamic.value.newsImage = response.data.url; // 解析并赋值新闻图片的URL
        ElMessage.success('图片上传成功'); // 上传成功的提示信息
      } else {
        console.error('上传失败：无效的响应数据', response.data);
        ElMessage.error('图片上传失败'); // 上传失败的提示信息
      }
    } catch (error) {
      console.error('上传失败', error);
      ElMessage.error('图片上传失败'); // 上传失败的提示信息
    }
  }
};

    return {
      query,
      items,
      deletedItems,
      currentPage,
      itemsPerPage,
      itemsPerPageOptions,
      sortOrder,
      editDialogVisible,
      editDynamic,
      detailDialogVisible,
      selectedDynamic,
      dialogPreviewVisible,
      search,
      navigateToCreate,
      toggleSortOrder,
      handlePageChange,
      deleteRow,
      undo,
      edit,
      saveEdit,
      showDynamicDetails,
      handlePictureCardPreview,
      handleImageChange,
      fileInput,
      selectImage,
      filteredItems,
      sortedItems,
      paginatedItems
    };
  }
});
</script>




<style scoped>
.container {
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  justify-content: center;
  align-items: center;
}

.query-input {
  width: 200px;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  margin-right: 10px;
}

.header-button {
  margin-left: 10px;
}

.data-table {
  width: 100%;
  background-color: #ffffff;
  border-radius: 8px;
  overflow: hidden;
}
.data-table .text-center {
  text-align: center;
}

.text-center {
  text-align: center;
}

.operation-buttons {
  display: flex;
  justify-content: space-around;
}

.operation-buttons .el-button {
  margin: 0 3px;
}

.sortable-header {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.sortable-header .el-icon {
  margin-left: 5px;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.items-per-page-select {
  width: 100px;
  margin-left: 20px;
}

.cover-image {
  width: 100%;
  height: auto;
  cursor: pointer;
}

.dialog {
  font-size: 16px;
}
.dialog-footer {
  text-align: right;
}

.preview-image {
  width: 100%;
  height: auto;
}
</style>
